package com.dwd.order.service.impl;

import com.dwd.basic.constant.PayConstants;
import com.dwd.basic.service.impl.BaseServiceImpl;
import com.dwd.basic.utils.CodeGenerateUtils;
import com.dwd.basic.utils.DistanceUtil;
import com.dwd.order.mapper.OrderAddressMapper;
import com.dwd.order.mapper.ProductOrderDetailMapper;
import com.dwd.order.mapper.ProductOrderMapper;
import com.dwd.order.mapper.UserAddressMapper;
import com.dwd.order.pojo.OrderAddress;
import com.dwd.order.pojo.ProductOrder;
import com.dwd.order.pojo.ProductOrderDetail;
import com.dwd.order.pojo.UserAddress;
import com.dwd.order.service.IProductOrderService;
import com.dwd.org.mapper.ShopMapper;
import com.dwd.org.pojo.Shop;
import com.dwd.pay.mapper.PayBillMapper;
import com.dwd.pay.pojo.PayBill;
import com.dwd.pay.service.IAliPayInfoService;
import com.dwd.quartz.pojo.QuartzJobInfo;
import com.dwd.quartz.service.IQuartzService;
import com.dwd.servicemanager.mapper.ProductMapper;
import com.dwd.servicemanager.pojo.Product;
import com.dwd.user.mapper.UserMapper;
import com.dwd.user.pojo.LoginInfo;
import com.dwd.user.pojo.User;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: TODO
 * @Author 汶狄
 * @Date 2021/1/27 18:02
 * @Version 1.0
 */
@Service
public class ProductOrderServiceImpl extends BaseServiceImpl<ProductOrder> implements IProductOrderService {
    @Autowired
    private ProductOrderMapper productOrderMapper;
    @Autowired
    private ProductOrderDetailMapper productOrderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IAliPayInfoService aliPayInfoService;
    @Autowired
    private IQuartzService quartzService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String submitOrder(Map<String, Object> map, LoginInfo loginInfo) {
        //查询对应的用户
        User user = userMapper.queryById(loginInfo.getId());
        Long addressId = Long.valueOf(map.get("addressId").toString());
        //通过地址id查询用户地址
        UserAddress userAddress = userAddressMapper.queryById(addressId);
        //创建订单地址
        OrderAddress orderAddress = createOrderAddress(userAddress, user);
        //保存订单地址
        orderAddressMapper.save(orderAddress);
        //创建产品订单
        ProductOrder productOrder = createProductOrder(orderAddress, user);
        //存储产品订单
        productOrderMapper.save(productOrder);
        //创建产品明细订单
        List<ProductOrderDetail> productOrderDetails = createProductOrderDetail(map, productOrder);
        //批量存储产品明细
        productOrderDetailMapper.batchSave(productOrderDetails);
        //修改总金额
        productOrderMapper.update(productOrder);
        //获取支付类型
        Integer payType = (Integer) map.get("payType");
        //创建支付订单对象
        PayBill payBill = createPayBill(productOrder, payType);
        //存储订单
        payBillMapper.save(payBill);
        //生成定时任务
        QuartzJobInfo quartzJobInfo = createQuartzTask(productOrder);
        //添加定时任务执行
        quartzService.addJob(quartzJobInfo);

        //根据对应支付状态跳转对应页面
        switch (payType) {
            //银联
            case 1:
                break;
            //微信
            case 2:
                break;
            //支付宝
            case 3:
                String result = aliPayInfoService.goBuy(productOrder);
                return result;
            default:
        }
        return "";

    }

    /**
     * 创建定时对象
     *
     * @param productOrder
     * @return
     */
    private QuartzJobInfo createQuartzTask(ProductOrder productOrder) {
        QuartzJobInfo quartzJobInfo = new QuartzJobInfo();
        quartzJobInfo.setType(PayConstants.BUSINESSTYPE_PRODUCT)
                .setJobName(PayConstants.BUSINESSTYPE_PRODUCT + productOrder.getOrderSn())
                .setFireDate(productOrder.getLastPayTime());
        //设置参数 只需要订单号
        HashMap<String, Object> params = new HashMap<>(16);
        params.put("OrderSn", productOrder.getOrderSn());
        quartzJobInfo.setParams(params);
        return quartzJobInfo;
    }

    /**
     * 创建订单对象
     *
     * @param productOrder
     * @param payType
     * @return
     */
    private PayBill createPayBill(ProductOrder productOrder, Integer payType) {
        PayBill payBill = new PayBill();
        payBill.setDigest("摘要：产品服务" + productOrder.getShop().getName())
                .setMoney(productOrder.getPrice())
                .setLastPayTime(productOrder.getLastPayTime())
                .setPayChannel(payType)
                .setBusinessType(PayConstants.BUSINESSTYPE_PRODUCT)
                .setBusinessKey(productOrder.getId())
                .setUser(productOrder.getUser())
                .setShop(productOrder.getShop())
                .setOrderSn(productOrder.getOrderSn());
        return payBill;
    }

    /**
     * 创建产品订单
     *
     * @param orderAddress
     * @param user
     * @return
     */
    private ProductOrder createProductOrder(OrderAddress orderAddress, User user) {
        ProductOrder productOrder = new ProductOrder();
        //分发给最近的门店
        Shop nearestShop = DistanceUtil.getNearestShop(DistanceUtil.getPoint(orderAddress.getFullAddress()), shopMapper.queryAll());
        productOrder.setDigest("欢迎来到" + nearestShop.getName() + "服务")
                .setOrderSn(orderAddress.getOrderSn())
                //不支付时间
                .setLastPayTime(DateUtils.addMinutes(new Date(), 2))
                .setUser(user)
                .setShop(nearestShop);
        return productOrder;
    }

    /**
     * 创建产品明细订单
     *
     * @param map
     * @param productOrder
     * @return
     */
    private List<ProductOrderDetail> createProductOrderDetail(Map<String, Object> map, ProductOrder productOrder) {
        //用来装每一个产品明细
        ArrayList<ProductOrderDetail> productOrderDetails = new ArrayList<>();
        //用来累计价格
        BigDecimal counts = new BigDecimal("0");
        //所有的产品明细
        List<Map<String, Integer>> products = (List<Map<String, Integer>>) map.get("products");
        //得到每一个产品
        for (Map<String, Integer> product : products) {
            ProductOrderDetail productOrderDetail = new ProductOrderDetail();
            //设置数量
            productOrderDetail.setSaleCount(product.get("num"));
            //查询对应的产品
            Product product1 = productMapper.queryProductById(Long.valueOf(product.get("id")));
            //设置产品
            productOrderDetail.setProduct(product1);
            //设置订单
            productOrderDetail.setOrder(productOrder);
            //添加到集合
            productOrderDetails.add(productOrderDetail);
            //累计金额
            counts = counts.add(product1.getSaleprice().multiply(new BigDecimal(productOrderDetail.getSaleCount().toString())));
        }
        //设置总金额
        productOrder.setPrice(counts);
        return productOrderDetails;
    }

    /**
     * 创建订单地址
     *
     * @param userAddress
     * @param user
     * @return
     */
    private OrderAddress createOrderAddress(UserAddress userAddress, User user) {
        OrderAddress orderAddress = new OrderAddress();
        //因为useraddress跟orderaddress字段相似度很高
        BeanUtils.copyProperties(userAddress, orderAddress);
        orderAddress.setCreateTime(new Date())
                .setOrderSn(CodeGenerateUtils.generateOrderSn(user.getId()));
        return orderAddress;
    }
}
